package com.eks.plus.service.impl;

import com.eks.plus.model.auto.UUserInfo;
import com.eks.plus.mapper.auto.UUserInfoMapper;
import com.eks.plus.service.IUUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.IntStream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenfenghai
 * @since 2020-09-28
 */
@Slf4j
@Service
public class UUserInfoServiceImpl extends ServiceImpl<UUserInfoMapper, UUserInfo> implements IUUserInfoService {

    @Autowired
    private PlatformTransactionManager transactionManager;

    List<TransactionStatus> transactionStatuses = Collections.synchronizedList(new ArrayList<TransactionStatus>());

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAll() {
        super.list();
        int count = 20;
        List<UUserInfo> userInfoList = new ArrayList<>(count);
        IntStream.range(0, count).forEach(i -> {
            UUserInfo user = new UUserInfo();
            user.setName("老王" + i);
            user.setTenantId("101");
            userInfoList.add(user);
        });

        List<List<UUserInfo>> partitionUserList = Lists.partition(userInfoList, 3);

        ForkJoinPool pool = new ForkJoinPool(4);
        pool.submit(()->{
                try{
                    // 使用这种方式将事务状态都放在同一个事务里面
                    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务，这样会比较安全些。
                    TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
                    transactionStatuses.add(status);


                    UUserInfo user = new UUserInfo();
                    user.setName("张三1");
                    user.setTenantId("101");
                    super.save(user);


                    user = new UUserInfo();
                    user.setName("张三2");
                    user.setTenantId("102");
                    super.save(user);
                }catch (Exception e){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    log.error("", e);
                }
        });
    }
}
